#include <iostream>
#include <string>
#include <cerrno>  // errno.h
#include <cstring> // string.h
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

const int size = 1024;

//获取其他信息
std::string getOtherMessage()
{
    static int cnt = 0;
    std::string messageid = std::to_string(cnt); // stoi -> string -> int
    cnt++;
    pid_t self_id = getpid();
    std::string stringpid = std::to_string(self_id);

    std::string message = "messageid: ";
    message += messageid;
    message += " my pid is : ";
    message += stringpid;

    return message;
}

//子进程写
void SubProcessWrite(int wfd)
{
    std::string message = "father, I am your son prcess!";
    while (true)
    {
        std::cout << "+++++++++++++++++++++++++++++++++++++++++++" << std::endl;
        std::string info = message + getOtherMessage();
        write(wfd, info.c_str(), info.size());
        std::cerr << info << std::endl;
        sleep(1);
    }
    std::cout << "child quit..." << std::endl;
}

//父进程读
void FatherProcessRead(int rfd)
{
    char inbuffer[size];
    while (true)
    {
        sleep(2);
        std::cout << "-------------------------------------------" << std::endl;
        ssize_t n = read(rfd, inbuffer, sizeof(inbuffer) - 1);
        if (n > 0)
        {
            inbuffer[n] = 0;
            std::cout << inbuffer << std::endl;
        }
        else if (n == 0)
        {
            std::cout << "client quit, father get return val: " << n << " father quit too!" << std::endl;
            break;
        }
        else
        {
            std::cerr << "read error" << std::endl;
            break;
        }
    }
    std::cout << "father quit..." << std::endl;
}

int main()
{
    int pipefd[2];
    int n = pipe(pipefd);
    if (n != 0)
    {
        std::cerr << "error:" << errno << ":" << "errstring:" << strerror(errno) << std::endl;
    }

    // pipefd[0]->0->r(嘴巴 - 读)  pipefd[1]->1->w(笔->写)
    // std::cout << "pipefd[0]: " << pipefd[0] << ", pipefd[1]: " << pipefd[1] << std::endl;
    // sleep(1);

    pid_t id = fork();
    if (id == 0)
    {
        // std::cout << "子进程关闭不需要的fd了, 准备发消息了" << std::endl;
        // sleep(1);
        close(pipefd[0]);

        // 进行写操作
        SubProcessWrite(pipefd[1]);

        // 写完成，正常退出
        close(pipefd[1]);
        exit(0);
    }

    std::cout << "父进程关闭不需要的fd了, 准备收消息了" << std::endl;
    sleep(1);

    close(pipefd[1]);
    FatherProcessRead(pipefd[0]);
    // std::cout << "5s, father close rfd" << std::endl;
    // sleep(5);
    close(pipefd[0]);

    // 父进程等待子进程
    int status = 0;
    pid_t rid = waitpid(id, &status, 0);
    if (rid > 0)
    {
        std::cout << "wait child process done, exit sig: " << (status & 0x7f) << std::endl;
        std::cout << "wait child process done, exit code(ign): " << ((status >> 8) & 0xff) << std::endl;
    }
    return 0;
}